import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  const darkMode = ref<boolean>(false) // 默认为暗黑主题
  
  // 初始化主题
  function initTheme() {
    // 检查本地存储
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
      darkMode.value = savedTheme === 'dark'
    } else {
      // 默认使用暗黑主题，不考虑系统偏好
      darkMode.value = false
      localStorage.setItem('theme', 'light')
    }
    
    // 应用主题到 HTML 元素
    applyTheme()
  }
  
  // 切换主题
  function toggleTheme() {
    darkMode.value = !darkMode.value
    localStorage.setItem('theme', darkMode.value ? 'dark' : 'light')
    applyTheme()
  }
  
  // 设置深色主题
  function setDarkTheme() {
    darkMode.value = true
    localStorage.setItem('theme', 'dark')
    applyTheme()
  }
  
  // 设置浅色主题
  function setLightTheme() {
    darkMode.value = false
    localStorage.setItem('theme', 'light')
    applyTheme()
  }
  
  // 应用主题到 HTML 元素
  function applyTheme() {
    if (darkMode.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 监听主题变化
  watch(darkMode, (newValue) => {
    applyTheme()
  })
  
  return {
    darkMode,
    initTheme,
    toggleTheme,
    setDarkTheme,
    setLightTheme
  }
}) 